<template>
  <div class="inventory-query">
    <!-- 搜索筛选栏 -->
    <div class="search-filter-bar">
      <el-select 
        v-model="searchForm.materialBrand" 
        placeholder="全部品牌" 
        clearable
        class="filter-select"
        @change="handleSearch"
      >
        <el-option label="全部品牌" value="" />
        <el-option 
          v-for="brand in brandOptions" 
          :key="brand" 
          :label="brand" 
          :value="brand" 
        />
      </el-select>
      
      <el-select 
        v-model="searchForm.materialSpecifications" 
        placeholder="全部型号" 
        clearable
        class="filter-select"
        @change="handleSearch"
      >
        <el-option label="全部型号" value="" />
        <el-option 
          v-for="spec in specificationOptions" 
          :key="spec" 
          :label="spec" 
          :value="spec" 
        />
      </el-select>
      
      <el-input
        v-model="searchForm.materialName"
        placeholder="请输入材料名称"
        class="search-input"
        @keyup.enter="handleSearch"
        clearable
      />
      
      <el-button type="primary" @click="handleSearch" class="search-btn">查询</el-button>
    </div>

    <!-- 库存数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        class="inventory-table" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column label="序号" type="index" width="100" align="center" />
        <el-table-column prop="materialName" label="材料名称" width="150" align="center" />
        <el-table-column prop="materialBrand" label="品牌" width="150" align="center" />
        <el-table-column prop="materialSpecifications" label="规格型号" width="150" align="center" />
        <el-table-column prop="materialPrice" label="单位成本" width="120" align="center">
          <template slot-scope="scope">
            {{ formatPrice(scope.row.materialPrice) }}
          </template>
        </el-table-column>
        <el-table-column prop="inventoryNum" label="当前库存" width="150" align="center" />
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.size"
        layout="prev, pager, next, jumper, sizes"
        :total="pagination.total"
        class="pagination"
      />
    </div>

    <!-- 修改库存对话框 -->
    <EditInventoryDialog
      :visible.sync="editDialogVisible"
      :inventory-data="currentInventory"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import { inventoryApi } from '@/api/inventory'
import EditInventoryDialog from './components/EditInventoryDialog.vue'

export default {
  name: 'InventoryQuery',
  components: {
    EditInventoryDialog
  },
  data() {
    return {
      loading: false,
      tableData: [],
      brandOptions: [],
      specificationOptions: [],
      searchForm: {
        materialName: '',
        materialBrand: '',
        materialSpecifications: ''
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      editDialogVisible: false,
      currentInventory: {}
    }
  },
  created() {
    this.loadData()
    this.loadBrandOptions()
    this.loadSpecificationOptions()
  },
  methods: {
    // 加载库存数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.current,
          size: this.pagination.size,
          materialName: this.searchForm.materialName || undefined,
          materialBrand: this.searchForm.materialBrand || undefined,
          materialSpecifications: this.searchForm.materialSpecifications || undefined
        }
        
        const response = await inventoryApi.getInventoryPage(params)
        if (response.code === 200) {
          this.tableData = response.data.records || []
          this.pagination.total = response.data.total || 0
          this.pagination.current = response.data.current || 1
        } else {
          this.$message.error(response.message || '查询失败')
        }
      } catch (error) {
        console.error('查询库存列表失败:', error)
        this.$message.error('查询失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 加载品牌选项
    async loadBrandOptions() {
      try {
        const response = await inventoryApi.getAllBrands()
        if (response.code === 200) {
          this.brandOptions = response.data || []
        }
      } catch (error) {
        console.error('加载品牌选项失败:', error)
      }
    },

    // 加载型号选项
    async loadSpecificationOptions() {
      try {
        const response = await inventoryApi.getAllSpecifications()
        if (response.code === 200) {
          this.specificationOptions = response.data || []
        }
      } catch (error) {
        console.error('加载型号选项失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.size = val
      this.pagination.current = 1
      this.loadData()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.current = val
      this.loadData()
    },

    // 修改库存
    handleEdit(row) {
      this.currentInventory = { ...row }
      this.editDialogVisible = true
    },

    // 修改成功回调
    handleEditSuccess() {
      this.loadData()
    },

    // 删除库存
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除这条库存记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await inventoryApi.deleteInventory(row.inventoryId)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除库存失败:', error)
          this.$message.error('删除失败，请稍后重试')
        }
      }
    },

    // 格式化价格
    formatPrice(price) {
      if (price === null || price === undefined) return '0.00'
      return Number(price).toFixed(2)
    }
  }
}
</script>

<style scoped>
.inventory-query {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索筛选栏样式 */
.search-filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-select {
  width: 160px;
  margin-right: 10px;
}

.search-input {
  width: 240px;
  margin-right: 10px;
}

.search-btn {
  padding: 10px 20px;
  font-size: 14px;
}

/* 表格容器样式 */
.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.inventory-table {
  width: 100%;
}

.inventory-table .el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.inventory-table .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin: 0;
}

/* 操作按钮样式 */
.el-button--text {
  color: #409eff;
  padding: 0;
  margin-right: 10px;
}

.el-button--text:hover {
  color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-select,
  .search-input {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .search-btn {
    width: 100%;
  }
}
</style>